package com.naja.event.tracking.extract.observer;

import com.naja.event.tracking.extract.domain.TBaseEvent;
import com.naja.event.tracking.extract.domain.TBizEvent;
import com.naja.event.tracking.extract.domain.TEventTraceAggregated;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @auther wangjianying
 * @date 2023/09/19 11:00
 */
public class MutuallyExclusiveBase2bizExtractObserver implements Base2bizExtractObserver{
    private List<SimpleBase2bizExtractObserver> simpleBase2BizExtractObservers = new ArrayList<>();
    private String firstTagEvent;
    private boolean begin =false;

    public MutuallyExclusiveBase2bizExtractObserver() {
    }

    public void addBase2bizExtractObserver(SimpleBase2bizExtractObserver simpleBase2BizExtractObserver) {
        this.simpleBase2BizExtractObservers.add(simpleBase2BizExtractObserver);
        if (firstTagEvent == null) {
            //互斥事件结束点都是一样的
            firstTagEvent = simpleBase2BizExtractObserver.getSortedTagEvents().get(0);
        }
    }

    public void update(TEventTraceAggregated tEventTraceAggregated, TBaseEvent tBaseEvent) {
        String rooterName = tBaseEvent.getRooterName();
        if (!StringUtils.isEmpty(rooterName)) {
            if (begin || (begin=firstTagEvent.equals(rooterName))) {
                for (SimpleBase2bizExtractObserver simpleBase2BizExtractObserver : this.simpleBase2BizExtractObservers) {
                    simpleBase2BizExtractObserver.update(tEventTraceAggregated, tBaseEvent);
                    if (simpleBase2BizExtractObserver.status()==0) {
                        begin = false;
                        //其中一条互斥线路完成,初始化其他线路
                        for (SimpleBase2bizExtractObserver innerSimpleBase2BizExtractObserver : this.simpleBase2BizExtractObservers) {
                            if (!innerSimpleBase2BizExtractObserver.equals(simpleBase2BizExtractObserver)) {
                                innerSimpleBase2BizExtractObserver.reset();
                            }
                        }
                    }
                }
            }
        }
    }
    public List<TBizEvent> getResult() {
        ArrayList<TBizEvent> tBizEvents = new ArrayList<>();
        for (SimpleBase2bizExtractObserver simpleBase2BizExtractObserver : this.simpleBase2BizExtractObservers) {
            tBizEvents.addAll(simpleBase2BizExtractObserver.getResult());
        }
        return tBizEvents;
    }

    @Override
    public void init() {
        begin = false;
        for (SimpleBase2bizExtractObserver simpleBase2BizExtractObserver : simpleBase2BizExtractObservers) {
            simpleBase2BizExtractObserver.init();
        }
    }
}
